<!--
 * @description  : 案件-市场检查表单
 * @descriptionDetail: 案件-市场检查表单
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-08-25 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar backText="返回" title="市场检查"></theme-navbar>
    <!-- #endif -->
    <view class="content">
      <u-form
        :model="marketForm"
        label-position="left"
        style="padding: 0px 15px;"
        :errorType="['border-bottom','message',]"
        label-width="auto"
        ref="marketFormRef"
      >
        <u-form-item label="承办单位" prop="orgShortname">
          <u-input
            type="text"
            input-align="right"
            :disabled="doc.isFinish"
            v-model="marketForm.orgShortname"
          />
        </u-form-item>
        <u-form-item label="检查人" prop="checkPerson" right-icon="arrow-right">
          <u-input
            type="text"
            input-align="right"
            placeholder="请选择"
            :disabled="true"
            v-model="marketForm.checkPerson"
            @tap="handlerSelectCheckers"
          />
        </u-form-item>
        <u-form-item label="检查单号" prop="fullDocNo">
          <u-input
            type="text"
            input-align="right"
            :disabled="doc.isFinish"
            placeholder="请填写检查单号"
            v-model="marketForm.fullDocNo"
          />
        </u-form-item>
        <u-form-item :required="true" label="检查时间" right-icon="arrow-right" prop="checkTime">
          <u-picker
            :params="{
              year: true,
              month: true,
              day: true,
              hour: true,
              minute: true,
              second: false,
              timestamp: true, // 1.3.7版本提供
            }"
            v-model="isShowTime"
            @confirm="timeChange"
          ></u-picker>
          <u-input
            :disabled="true"
            input-align="right"
            placeholder="请选择检查时间"
            v-model="marketForm.checkTime"
            @click="()=>{if(!doc.isFinish) isShowTime = true}"
          />
        </u-form-item>
        <u-form-item label="线索来源" :required="true" prop="clueSource">
          <dic-input
            :keyWord="$u.dic.DIC_KEYS.CLUE_SOURCE"
            :dicCode="marketForm.clueSource"
            :border="false"
            inputAlign="right"
            type="select"
            :select-open="dicSelectOpen('clueSource',$u.dic.DIC_KEYS.CLUE_SOURCE)"
            placeholder="请选择"
            :disabled="true"
            v-model="marketForm.clueSourceStr"
            @changeInputModelData="(name)=>{$set(marketForm, 'clueSourceStr', name)}"
            @click="showDic($u.dic.DIC_KEYS.CLUE_SOURCE,marketForm.clueSource,'clueSource')"
          />
        </u-form-item>
        <u-form-item :required="true" label="当事人" prop="party">
          <u-input
            type="text"
            input-align="right"
            placeholder="请填写当事人"
            :disabled="doc.isFinish"
            v-model="marketForm.party"
          />
        </u-form-item>
        <u-form-item
          label="检查实施清单"
          label-position="top"
          prop="checkActionCode"
          right-icon="arrow-right"
          class="parent-ico row"
        >
          <u-input
            :disabled="true"
            type="textarea"
            height="70"
            placeholder="请选择"
            v-model="marketForm.checkActionCodeName"
            @click="()=>{if(!doc.isFinish) chooseCheckCode()}"
          />
        </u-form-item>
        <u-form-item label="案发地点" prop="caseAddr" label-position="top">
          <u-input
            type="textarea"
            :disabled="doc.isFinish"
            placeholder="请填写案发地点"
            v-model="marketForm.caseAddr"
          />
        </u-form-item>
        <u-form-item label="案情陈述" label-position="top" prop="caseBrief">
          <u-input
            type="textarea"
            :disabled="doc.isFinish"
            placeholder="这里输入案情简述"
            v-model="marketForm.caseBrief"
          />
        </u-form-item>
        <u-form-item label="备注" label-position="top" prop="remark">
          <u-input
            type="textarea"
            :disabled="doc.isFinish"
            placeholder="这里输入备注"
            v-model="marketForm.remark"
          />
        </u-form-item>
      </u-form>
    </view>
    <view class="submit-btns" v-if="!doc.isFinish">
      <u-button plain class="del" type="success" @click="submit(false)">
        保存
      </u-button>
      <u-button plain class="mit" type="primary" @click="submit(true)">
        提交
      </u-button>
    </view>
    <!-- 检查人: 从检查中选人，不要从全组织选 -->
    <u-popup mode="bottom" border-radius="14" height="80%" v-if="dayUuid" v-model="personShow">
      <multi-select :options="personOptions" @select="handlerSelectPersons"></multi-select>
    </u-popup>
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-else v-model="personShow">
      <org-person-select treeType="zm-case" @choose="handlerSelectPersons"></org-person-select>
    </u-popup>
    <!-- 下拉选择用 -->
    <dic-choice
      :keyWord="dicKeyWords"
      :currentSelect="dicCurrentSelect"
      v-model="dicShow"
      @confirm="selectDicConfirm"
    ></dic-choice>
  </view>
</template>

<script>
import OrgPersonSelect from "@/components/org-person-select.vue";
import multiSelect from "@/components/multi-select.vue"
import {
  CASE_SOURCE,
  CASE_SOURCE_NAME,
} from '@/service/case/mapping/index.js';
import DicChoice from "@/components/dic_choice.vue";
import DicInput from "@/components/dic_input.vue";
import certificateService from "@/service/certificate/certificate.service.js";
import commonService from '@/service/common/common.service';
import caseService from '@/service/case/case.service';
export default {
  components: {
    OrgPersonSelect,
    multiSelect,
    DicChoice,
    DicInput,
  },
  mixins: [],
  onLoad() {
    let param = this.getRouteParam();
    console.log("参数", param);
    if (param == undefined) return;
    this.dataFromCheck = param.retailer;
    this.marketForm.checkTime = this.$u.date(Date.now(), 'yyyy年mm月dd日 hh时MM分');
    if (this.dataFromCheck) {
      this.marketForm.party = this.dataFromCheck.managerName;
      this.marketForm.caseAddr = this.dataFromCheck.businessAddr;
      this.marketForm.checkActionCode = this.dataFromCheck.checkActionCode;
      this.marketForm.checkActionCodeName = this.dataFromCheck.checkActionCodeName;
    } else {
      this.dataFromCheck = {};
    }
    this.isRegisterCase = param.isRegisterCase;
    this.docInsUuid = param.docInsUuid;
    this.dayUuid = param.dayUuid;
    this.isBack = param.isBack;
  },
  data() {
    return {
      dicType: "",
      dicShow: false,
      // dic 关键字
      dicKeyWords: "",
      // dic 当前选择项
      dicCurrentSelect: "",
      personShow: false,
      isShowTime: false, // 控制时间显示与隐藏弹框
      personOptions: [], // 从检查过来的检查人员选择
      // 市场检查表单
      marketForm: {
        checkBillUuid: "",
        cluesUuid: "",
        caseUuid: "",
        orgShortname: "",
        docYear: "",
        fullDocNo: "",
        checkPerson: "",
        checkTime: "",
        party: "",
        caseAddr: "",
        caseProp: "",
        caseBrief: "",
        finished: false,
        remark: "",
        isActive: false,
        creator: "",
        createTime: "",
        modifier: "",
        modifyTime: "",
        ownDeptUuid: "",
        ownOrgUuid: "",
        checkActionCode: "",
        checkActionCodeName: "",
      },
      // 表单规则校验
      rules: {
        checkTime: [{
          required: true,
          message: "请选择举报时间",
          trigger: ["change",],
        },],
        party: [{
          required: true,
          message: "请填写当事人",
          trigger: ["blur",],
        },],
        clueSource: [{
          required: true,
          message: "请选择线索来源",
          trigger: ["blur",],
        },],
      },
      dataFromCheck: {}, // 从市场检查过来的数据
      isRegisterCase: false,
      docInsUuid: "",
      dayUuid: "",
      isBack: false,
      doc: {},
      user: this.$storage.get(this.$rp.common.USER),
    }
  },
  onReady() {
    this.$refs.marketFormRef.setRules(this.rules)
  },
  mounted() {
    this.init();
    this.marketForm.orgShortname = this.user.docOrgName;
    if (this.docInsUuid) {
      caseService.getSourceClueInfoById(this.docInsUuid).then(res => {
        if (!res.success) return;
        this.objMerge(this.doc, res.bean);
        caseService.getSourceClueDocInfo(this.doc.docInsUuid, this.doc.docUuid, this.doc.bizUuid).then(
          (abs) => {
            if (!abs.success) return;
            let markets = abs.data;
            markets.length > 0 && this.objMerge(this.marketForm, markets[0]);
          });
      });
    } else {
      this.getDayPlanCheckers();
    }
  },
  methods: {
    init() {

    },
    dicSelectOpen(type, keyWords) {
      if (type == this.dicType) {
        if (this.dicKeyWords == keyWords && this.dicShow) {
          return true;
        }
        return false;
      }
    },
    showDic(key, cur, type) {
      if (this.dicShow || this.doc.isFinish) return;
      this.dicKeyWords = key;
      this.dicCurrentSelect = cur;
      this.dicShow = true;
      this.dicType = type;
    },
    /**
			 * @description 下拉选中确定事件，处理选中的结果绑定至数据
			 * @params e 选中的结果数据
			 */
    selectDicConfirm(e) {
      if (this.dicKeyWords == this.$u.dic.DIC_KEYS.CLUE_SOURCE) { // 未办证原因
        this.marketForm.clueSourceStr = e[0].label;
        this.marketForm.clueSource = e[0].extra.bcbCode;
      }
    },
    /**
			 * 查询默认的检查人
			 */
    getDayPlanCheckers() {
      // 查询检查人员
      this.dayUuid && certificateService.getCheckPersons(this.dayUuid).then(
        dr => {
          if (dr.success) {
            let ps = dr.data;
            let pNames = [];
            ps.map(p => {
              p.uid = p.personUuid;
              p.name = p.personName;
              p.exts = [p.certNo, p.mainJobName,];
              pNames.push(p.personName);
            });
            this.marketForm.checkPerson = pNames.join(",");
            this.$nextTick(() => this.personOptions = ps);
          }
        });
    },
    // 选择检查人员
    handlerSelectCheckers() {
      if (this.doc.isFinish) return;
      this.personShow = true;
    },
    // 选中的检查人员
    handlerSelectPersons(items) {
      if (items.length == 0) {
        this.$u.toast("请选择检查人员");
        return;
      }
      let pNames = [];
      items.forEach(p => pNames.push(p.name));
      this.marketForm.checkPerson = pNames.join(",");
      this.personShow = false;
    },
    // 跳转到选择检查编码页面
    chooseCheckCode() {
      if (this.dataFromCheck.from == 'check') {
        this.$modal.alert("修改检查清单将脱离日常检查来源, 是否继续?", "提示", () => {
          this.$u.route({
            url: "/pages/case/sourceregister/checkcodeselect",
            params: {
              isSingle: true,
            },
            type: "to",
          });
        }, '确定', true);
      } else {
        this.$u.route({
          url: "/pages/case/sourceregister/checkcodeselect",
          params: {
            isSingle: true,
          },
          type: "to",
        });
      }
    },
    updateBackState(obj) {
      if (obj.backCheckCode) {
        this.marketForm.checkActionCode = obj.backCheckCode[0].jgsxDealUuid;
        this.marketForm.checkActionCodeName = obj.backCheckCode[0].superviseItemName;
      }
    },
    // 提交表单
    submit(isSubmit) {
      this.$refs.marketFormRef.validate(valid => {
        if (!valid) return;
        this.$modal.showLoading("保存中...");
        caseService.saveMarketDoc(this.marketForm).then((dr) => {
          this.$modal.hideLoading();
          if (!dr.success) {
            this.$modal.alert("保存失败:" + dr.msg);
            return;
          }
          this.marketForm.checkBillUuid = dr.bean.checkBillUuid;
          this.marketForm.cluesUuid = dr.bean.cluesUuid;
          if (isSubmit) {
            this.$modal.showLoading("提交中...");
            caseService.submitMarketDoc(this.marketForm, dr.data[0].docInsUuid).then((
              sdr) => {
              this.$modal.hideLoading();
              if(!sdr.success){
                this.$modal.alert('提交失败:' + sdr.msg);
                return;
              }
              if (this.isRegisterCase) {
                this.$modal.alert("提交成功，是否直接立案？", "提示", () => {
                  this.setRouteParam({
                    initQueryData: {
                      cluesUuid: dr.bean.cluesUuid,
                      party: this.marketForm.party,
                    },
                  });
                  this.$u.route({
                    url: '/pages/case/components/caseFilingLink',
                    type: 'redirect',
                    params: {
                      caseType: 1,
                    },
                  });
                }, "确定", true, () => {
                  this.backPrev({
                    paramKey: "refreshBack",
                    param: true,
                  });
                });
              } else {
                this.$modal.alert("提交成功", () => {
                  this.backPrev({
                    paramKey: "refreshBack",
                    param: true,
                  });
                });
              }
            }).catch(error => {
              this.$modal.hideLoading();
              this.$modal.alert("保存失败:" + error);
              console.error(error);
            });
          } else {
            this.$modal.alert("保存成功", () => {
              this.backPrev({
                paramKey: "refreshBack",
                param: true,
              });
            });
          }
        }).catch(err => {
          this.$modal.hideLoading();
          this.$modal.alert("保存失败:" + err);
          console.error(err);
        });
      })
    },
    timeChange(e) {
      this.marketForm.checkTime = this.$u.date(e.timestamp, 'yyyy年mm月dd日 hh时MM分');
    },
  },
};
</script>

<style lang="scss" scoped>
	@import "@/style/common/rightMenu.scss";

	.submit-btns {
		display: flex;
		position: fixed;
		bottom: 40rpx;
		left: 40rpx;
		right: 40rpx;
		text-align: center;

		.del {
			flex: 1;
		}

		.mit {
			flex: 1;
			margin-left: 40rpx;
		}
	}
</style>
